import math
import os
import time
import sys

# 将工程目录加入包扫描
currPath = os.path.abspath(os.path.dirname(__file__))
srcPath = os.path.split(currPath)[0]
rootPath = os.path.split(srcPath)[0]
projectPath = os.path.split(rootPath)[0]
sys.path.append(projectPath)

from src.db.CcxDataCenterDb import CcxDataCenter
from src.db.FCDB import FCDB
from src.db.ProdDb import ProdDb
from src.tasks.enterprise.SyncEnterpriseBaseInfo import SyncEnterpriseBaseInfo
from src.tasks.enterprise.SyncEnterpriseNameList import SyncEnterpriseNameList
from src.tasks.enterprise.SyncEnterpriseRatingData import SyncEnterpriseRatingData
from src.tasks.enterprise.SyncEnterpriseSecuritiesData import SyncSecuritiesData
from src.utils.CommonUtils import cleanScreen
from src.utils.LogUtils import Logger


# 主函数
def main():
    logger = Logger()
    cleanScreen()

    localDb = ProdDb(logSql=False, autocommit=True)
    dataCenterDb = CcxDataCenter(logSql=False, autocommit=True)
    fcdb = FCDB(logSql=False, autocommit=True)

    t = time.perf_counter()

    logger.info("========同步主体信息 开始 ========")

    # 同步主体名单
    nameList = SyncEnterpriseNameList(logger=logger, localDb=localDb, dcdb=dataCenterDb)
    enterpriseList, deleteCodes = nameList.getEnterpriseList()

    # 更新主体基础信息
    baseInfo = SyncEnterpriseBaseInfo(logger=logger, localDb=localDb, dataCenterDb=dataCenterDb, fcdb=fcdb)
    baseInfo.update(enterpriseList)

    # 更新评级信息
    ranting = SyncEnterpriseRatingData(logger=logger, localDb=localDb, dataCenterDb=dataCenterDb, fcdb=fcdb)
    ranting.update(enterpriseList)

    # 更新存续债
    securities = SyncSecuritiesData(logger=logger, localDb=localDb, fcdb=fcdb)
    securities.update(enterpriseList)

    # 写入到数据库
    baseInfo.writedb(enterpriseList, deleteCodes)

    cast = (time.perf_counter() - t)
    m = math.floor(cast / 60)
    s = cast - m * 60
    logger.info('总耗时: %d分%.3f秒' % (m, s))
    logger.info("========同步主体信息 结束 ========")


# 程序入口
if __name__ == "__main__":
    main()
